package FileMangerClient;

import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.util.Arrays;

import Controllers.Context;
import DiskManager.Disk;
import DiskManager.DiskBit;
import FileManager.SimulateContent;
import FileManager.SimulationDirectory;
import FileManager.SimulationFile;
import Tools.AddSomething;
import Tools.Wordwin;
import javafx.application.Application;
import javafx.event.EventHandler;
import javafx.fxml.FXMLLoader;
import javafx.scene.Parent;
import javafx.scene.Scene;
import javafx.scene.control.TreeItem;
import javafx.stage.Stage;
import javafx.stage.StageStyle;
import javafx.stage.WindowEvent;
 
public class FileMain {
	static StringBuilder saveContent = new StringBuilder();
	static Disk disk = new Disk();
	Stage primaryStage;
    /*public static void main(String[] args) {
       readSaveContent();
       launch(args);
       getSaveContent();
   	   writeSaveContent(); 
    }
    
    @Override
    public void start(Stage stage) throws Exception {
    
    	Parent root = FXMLLoader.load(getClass().getResource("/FileMangerClient/MyComputer.fxml"));
        Scene scene = new Scene(root, 900, 600);
        stage.initStyle(StageStyle.DECORATED);
        stage.setScene(scene);
        stage.show();
        MyComputerController myComputerController = (MyComputerController)Context.controllers.get(MyComputerController.class.getSimpleName());
        System.out.print(myComputerController.getS());
        myComputerController.setDisk(disk);
        myComputerController.setS("硬盘已成功传入Controller\n");
        System.out.print(myComputerController.getS());
        initializeDisk(myComputerController.Folder_C,myComputerController);
        initializeDisk(myComputerController.Folder_D,myComputerController);
        initializeDisk(myComputerController.Folder_E,myComputerController);
        initializeDisk(myComputerController.Folder_F,myComputerController);
    }*/
	public FileMain() {
		try {
			readSaveContent();
			primaryStage = new Stage();
			Parent root = FXMLLoader.load(getClass().getResource("/FileMangerClient/MyComputer.fxml"));
	        Scene scene = new Scene(root, 900, 600);
	        primaryStage.initStyle(StageStyle.DECORATED);
	        primaryStage.setScene(scene);
	        primaryStage.setOnCloseRequest(new EventHandler<WindowEvent>() {
	            @Override
	            public void handle(WindowEvent event) {
	    	        primaryStage.hide();
	            	getSaveContent();
	            	writeSaveContent(); 
	            }
	          });
	      MyComputerController myComputerController = (MyComputerController)Context.controllers.get(MyComputerController.class.getSimpleName());
	      myComputerController.setDisk(disk);
	        myComputerController.setS("硬盘已成功传入Controller\n");
	        System.out.print(myComputerController.getS());
	        initializeDisk(myComputerController.Folder_C,myComputerController);
	        initializeDisk(myComputerController.Folder_D,myComputerController);
	        initializeDisk(myComputerController.Folder_E,myComputerController);
	        initializeDisk(myComputerController.Folder_F,myComputerController);
		} catch(Exception e) {
			e.printStackTrace();
		}
	}
	 public static void writeSaveContent() {
		 File file = new File("DiskContent.txt");
		 if(!file.exists()){
	            try {
	                file.createNewFile();
	            } catch (IOException e) {
	                e.printStackTrace();
	            }
	        }
		 try (BufferedWriter writer = new BufferedWriter(new FileWriter(file.getPath(),false));) {
				writer.write(saveContent.toString());
				writer.close();
			} catch (Exception e) {
				e.printStackTrace();
			}
	 }
	 
	 
	 public static void getSaveContent() {
		 DiskBit[] diskbit = disk.getDiskBit();
		 char[] content = null;
		 int[] FAT = disk.getFAT();
		 for(int i=0;i<256;i++) {
			 saveContent.append(String.format("%03d",FAT[i]));
			 if(i==127)saveContent.append("\n");
		 }
		 saveContent.append("\n");
		 MyComputerController myComputerController = (MyComputerController)Context.controllers.get(MyComputerController.class.getSimpleName());
		 String basicdisk = "";
		 basicdisk=String.format("%6s",myComputerController.Folder_C.getName())+String.format("%2s",myComputerController.Folder_C.getExtendName())+String.format("%1s",myComputerController.Folder_C.getAttribute())+String.format("%3d",myComputerController.Folder_C.getStartnum())+String.format("%4d",myComputerController.Folder_C.getSize())+" "
		          +String.format("%6s",myComputerController.Folder_D.getName())+String.format("%2s",myComputerController.Folder_D.getExtendName())+String.format("%1s",myComputerController.Folder_D.getAttribute())+String.format("%3d",myComputerController.Folder_D.getStartnum())+String.format("%4d",myComputerController.Folder_D.getSize())+" "
		          +String.format("%6s",myComputerController.Folder_E.getName())+String.format("%2s",myComputerController.Folder_E.getExtendName())+String.format("%1s",myComputerController.Folder_E.getAttribute())+String.format("%3d",myComputerController.Folder_E.getStartnum())+String.format("%4d",myComputerController.Folder_E.getSize())+" "
		          +String.format("%6s",myComputerController.Folder_F.getName())+String.format("%2s",myComputerController.Folder_F.getExtendName())+String.format("%1s",myComputerController.Folder_F.getAttribute())+String.format("%3d",myComputerController.Folder_F.getStartnum())+String.format("%4d",myComputerController.Folder_F.getSize());
		 diskbit[2].save(basicdisk.toCharArray());
		 
		 for(int i =2;i<256;i++) {
			 content = diskbit[i].load();
			 for(int j=0;j<content.length;j++) {
				 saveContent.append(content[j]);
			 }
			 saveContent.append("\n");
		 }
	 }
	 
	 
	 public static void readSaveContent() {
	    	String readContent = null;
	    	try (BufferedReader bufferedReader = new BufferedReader(new FileReader("DiskContent.txt"));){
	    		readContent = bufferedReader.readLine();
	    		for(int i=0;i<2;i++) {
	    			createFAT(readContent,i);
	    			readContent = bufferedReader.readLine();
	    		}
	    		for(int i=2;i<256;i++) {
	    			createDiskbit(readContent, i);
	    			readContent = bufferedReader.readLine();
	    		}
	    		bufferedReader.close();
	        } catch (IOException e) {
	            e.printStackTrace();
	        }
	    }
	    
	 private static void createFAT(String string,int time) {//需修改
		 int start = 0;
		 int end = 3;
		 int[] fat = disk.getFAT();
		 for(int i=0+time*128;i<128+time*128;i++) {
			 String content = string.substring(start,end);
			 int fatcontent = Integer.parseInt(content);
			 fat[i] = fatcontent;
			 start+=3;
			 end+=3;
		 }
	 }
	 
	 private static void createDiskbit(String string,int time) {
		 DiskBit[] diskbit = disk.getDiskBit();
		 diskbit[time].save(string.toCharArray());
	 }
	 
	    private void initializeDisk(SimulationDirectory directory,MyComputerController myComputerController) {
	    	int Num = 0;
	    	int start = 0;
	    	switch(directory.getName()){
	    		case("C"):Num = 3;break;
	    		case("D"):Num = 63;break;
	    		case("E"):Num = 123;break;
	    		case("F"):Num = 183;break;
	    	}
	    	if(directory.getStartnum()!=2) {
	    	    Num = directory.getStartnum();
	    	    start = 16;
	    	}
	    	int[] fat = disk.getFAT();
	    	DiskBit[] diskbit = disk.getDiskBit();
	    	char[] load = diskbit[Num].load();
	    	char[] charnum = new char[3];
	    	for(int i=start;i<load.length;i++) {
    			if(load[i]!='0'&&load[i]!='1'&&load[i]!='2'&&load[i]!='3'&&load[i]!='4'&&load[i]!='5'&&load[i]!='6'&&load[i]!='7'&&load[i]!='8'&&load[i]!='9')load[i]=' ';
    		}
	    	for(;start<=125;) {
	    		System.arraycopy(load, start, charnum, 0, 3);
	    		String stringnum = new String(charnum).replaceAll(" ","0");
	    		int nextNum = Integer.parseInt(stringnum);
	    		if(nextNum==0) {
	    			start+=3;
	    			continue;
	    		}
	    		char[] nextload = diskbit[nextNum].load();
	    		String Schildcontent = new String(nextload);
	    		char[] childcontent = Schildcontent.toCharArray();
	    		char[] charname = new char[6];
	    		char[] charExtendName = new char[2];
	    		char[] charattribute = new char[1];
	    		char[] charstartnum  = new char[3];
	    	    char[] charsize = new char[4];
	    	    System.arraycopy(childcontent, 0, charname, 0, 6);
	    	    System.arraycopy(childcontent, 6, charExtendName, 0, 2);
	    	    System.arraycopy(childcontent, 8, charattribute, 0, 1);
	    	    System.arraycopy(childcontent, 9, charstartnum, 0, 3);
	    	    System.arraycopy(childcontent, 12, charsize, 0, 4);
	    	    String name = new String(charname).replace(" ","");
	    	    String extendname = new String(charExtendName).replace(" ","");
	    	    String attribute = new String(charattribute).replace(" ","");
	    	    String startnum = new String(charstartnum).replace(" ","");
	    	    String size = new String(charsize).replace(" ","");
	    	    if(attribute.equals("T")||attribute.equals("E")) {
	    	    	SimulationFile file = new SimulationFile(name,extendname,attribute,Integer.parseInt(startnum),directory,Integer.parseInt(size),disk);
	    	    	file.initialize(disk);
	    	    }
	    	    else {
	    	    	SimulationDirectory dir = new SimulationDirectory(name,extendname,attribute,Integer.parseInt(startnum),directory,disk);
	    	    	//dir.initialize(disk);
	    	    	AddSomething addSomething = new AddSomething();
	    	    	dir.setTreeItem(new TreeItem<String>(dir.getName()));
	    			addSomething.AddTreeItem(dir,dir.getFather(),myComputerController.getFlowPane());
	    		    myComputerController.simulationDirectorys.add(dir);
	    		    System.out.println(dir.getFather().getName());
	    	    	initializeDisk(dir,myComputerController);
	    	    }
	    	    start+=3;
	    	}
	    	return;
	    }
 
	   public void setprimaryStage() {
		   this.primaryStage.show();
	}
}
